import 'dart:convert';
import 'package:crypto/crypto.dart';
import 'package:intl/intl.dart';
import 'package:http/http.dart' as http;

class AsrConfig {
  final String secretId;
  final String secretKey;
  final String region;
  final String engineModelType = '16k_zh'; // 默认为16k_zh
  final int resTextFormat = 0; // 默认为0
  final int channelNum = 1; // 默认为1

  AsrConfig({
    required this.secretId,
    required this.secretKey,
    required this.region,
  });
}

class AsrClient {
  final AsrConfig config;
  AsrClient({required this.config});

  String _getTimestamp() {
    return (DateTime.now().toUtc().millisecondsSinceEpoch ~/ 1000).toString();
  }

  String _getDate() {
    final now = DateTime.now().toUtc();
    return DateFormat('yyyy-MM-dd').format(now);
  }

  String _buildAuthorization({
    required String service,
    required String action,
    required String version,
    required String timestamp,
    required String payload,
  }) {
    final date = _getDate();
    final credentialScope = '$date/$service/tc3_request';
    final hashedRequestPayload = sha256.convert(utf8.encode(payload)).toString();
    
    final canonicalRequest = [
      'POST',
      '/',
      '',
      'content-type:application/json; charset=utf-8',
      'host:asr.tencentcloudapi.com',
      'x-tc-action:${action.toLowerCase()}',
      'x-tc-region:${config.region}',
      'x-tc-timestamp:$timestamp',
      'x-tc-version:$version',
      '',
      'content-type;host;x-tc-action;x-tc-region;x-tc-timestamp;x-tc-version',
      hashedRequestPayload,
    ].join('\n');

    final hashedCanonicalRequest = sha256.convert(utf8.encode(canonicalRequest)).toString();
    
    final stringToSign = [
      'TC3-HMAC-SHA256',
      timestamp,
      credentialScope,
      hashedCanonicalRequest,
    ].join('\n');

    final secretDate = Hmac(sha256, utf8.encode('TC3${config.secretKey}')).convert(utf8.encode(date));
    final secretService = Hmac(sha256, secretDate.bytes).convert(utf8.encode(service));
    final secretSigning = Hmac(sha256, secretService.bytes).convert(utf8.encode('tc3_request'));
    final signature = Hmac(sha256, secretSigning.bytes).convert(utf8.encode(stringToSign)).toString();

    return 'TC3-HMAC-SHA256 '
        'Credential=${config.secretId}/$credentialScope, '
        'SignedHeaders=content-type;host;x-tc-action;x-tc-region;x-tc-timestamp;x-tc-version, '
        'Signature=$signature';
  }

  /// 发送录音文件识别任务
  Future<Map<String, dynamic>> createRecTask({
    required String url,
  }) async {
    final endpoint = 'https://asr.tencentcloudapi.com/';
    final timestamp = _getTimestamp();
    final service = 'asr';
    final action = 'CreateRecTask';
    final version = '2019-06-14';

    // 构造请求体
    final Map<String, dynamic> body = {
      'EngineModelType': config.engineModelType,
      'ChannelNum': config.channelNum,
      'ResTextFormat': config.resTextFormat,
      'SourceType': 0,
      "Url": url,
    };

    final payload = jsonEncode(body);

    // 构造头部
    final headers = <String, String>{
      'Content-Type': 'application/json; charset=utf-8',
      'Host': 'asr.tencentcloudapi.com',
      'X-TC-Action': action,
      'X-TC-Version': version,
      'X-TC-Timestamp': timestamp,
      'X-TC-Region': config.region,
    };

    // 生成签名
    final auth = _buildAuthorization(
      service: service,
      action: action,
      version: version,
      timestamp: timestamp,
      payload: payload,
    );
    headers['Authorization'] = auth;

    // 发送请求
    final response = await http.post(
      Uri.parse(endpoint),
      headers: headers,
      body: payload,
    );

    return jsonDecode(response.body);
  }

  /// 查询录音文件识别任务
  Future<Map<String, dynamic>> describeTaskStatus(int taskId) async {
    final endpoint = 'https://asr.tencentcloudapi.com/';
    final timestamp = _getTimestamp();
    final service = 'asr';
    final action = 'DescribeTaskStatus';
    final version = '2019-06-14';

    // 构造请求体
    final Map<String, dynamic> body = {
      'TaskId': taskId,
    };

    final payload = jsonEncode(body);

    // 构造头部
    final headers = <String, String>{
      'Content-Type': 'application/json; charset=utf-8',
      'Host': 'asr.tencentcloudapi.com',
      'X-TC-Action': action,
      'X-TC-Version': version,
      'X-TC-Timestamp': timestamp,
      'X-TC-Region': config.region,
    };

    // 生成签名
    final auth = _buildAuthorization(
      service: service,
      action: action,
      version: version,
      timestamp: timestamp,
      payload: payload,
    );
    headers['Authorization'] = auth;

    // 发送请求
    final response = await http.post(
      Uri.parse(endpoint),
      headers: headers,
      body: payload,
    );

    return jsonDecode(response.body);
  }
}
